<template>
  <a-modal
    title="财务审核"
    :width="1280"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24" v-if="this.model.creditAuthorizeFlag==1">
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="授信订单：">
              授信金额 {{ this.creditLimit }}
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="已使用">
              {{ this.usedCreditLimit }} 元
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="剩余">
              {{ this.remainCreditLimit }}元
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单编号">
              {{ this.model.id }}
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="应付金额">
              {{ this.model.payAmount }}
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="申请后金额">
              {{ goodsTotalAmount }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="请选择">
              <j-dict-select-tag
                v-decorator="['orderFlag', validatorRules.status]"
                @change="handleWarehouseFlag"
                :type="'radioButton'"
                :triggerChange="true"
                dictCode="orderFinanceReview_status"
              />
            </a-form-item>
            <a-form-item
              :hidden="model.orderFlag == 1"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="拒绝备注"
            >
              <a-textarea
                v-if="model.orderFlag != 1"
                :rows="1"
                placeholder="请输入拒绝备注"
                v-decorator="['note', validatorRules.note]"
              />
            </a-form-item>
          </a-col>
          <a-col>
            <div style="color: red; font-weight: bold;font-size: large; " v-if="skuStockWaring.length>0">
              存在商品库存不足
            </div>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        size="middle"
        :columns="goodsColumns"
        :dataSource="goodsData"
        :scroll="{ y: 440 }"
        :pagination="false"
        :loading="loading"
      >
        <div slot="realAmount" slot-scope="realAmount, row">
          <a-input-number
            id="inputNumber1"
            :value="realAmount"
            :min="0"
            @change="onChangeAmount($event, row)"
            :precision="2"
            :disabled="row.orderProductType == 1"
          />
        </div>
        <div slot="productQuantity" slot-scope="productQuantity, row">
          <a-input-number
            id="inputNumber2"
            :precision="0"
            :value="productQuantity"
            :min="1"
            @change="onChangeQuantity($event, row)"
          />
        </div>
        <div slot="stock_warning" slot-scope="stock_warning, row">
          <a-space >
            <div style="color: red;"  v-if="row.productQuantity>row.stock">
              {{stock_warning}}
            </div>
            <div  v-if="row.productQuantity<=row.stock">
              {{stock_warning}}
            </div>
          </a-space>
        </div>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from "lodash.pick";
import { httpAction } from "@/api/manage";
import { getAction } from "@/api/manage";

export default {
  name: "OmsOrderFinanceEditApplyModal",

  data() {
    return {
      visible: false,
      confirmLoading: false,
      isChanged: false,
      creditLimit:0,
      remainCreditLimit:0,
      usedCreditLimit:0,
      skuStockWaring:[],
      note: "",
      validatorRules: {
        status: { rules: [{ required: true, message: "请选择状态!" }] },
        note: { rules: [{ required: true, message: "请输入拒绝原因!" }] },
      },
      model: {},
      disableSubmit: false,
      goodsColumns: [
        {
          title: "名称",
          key: "productName",
          width:200,
          dataIndex: "productName",
        },
        {
          title: '箱规',
          key: 'boxUnit',
          width:80,
          dataIndex: 'boxUnit'
        },
        {
          title: "商品类型",
          key: "orderProductType_dictText",
          dataIndex: "orderProductType_dictText",
        },
        {
          title: "货号",
          key: "productSn",
          dataIndex: "productSn",
        },
        {
          title: "物料编码",
          key: "productSkuCode",
          dataIndex: "productSkuCode",
        },
        {
          title: "商品单价",
          key: "productPrice",
          dataIndex: "productPrice",
        },
        {
          title: "实际单价",
          key: "productPrice",
          dataIndex: "realAmount",
        },
        {
          title: "小计",
          key: "totalRealAmount",
          dataIndex: "totalRealAmount",
        },
        {
          title: "库存",
          key: "stock",
          dataIndex: "stock_warning",
          scopedSlots: {customRender: "stock_warning"},
        },
        {
          title: "数量",
          dataIndex: "productQuantity",
          scopedSlots: { customRender: "productQuantity" },
        },
      ],
      goodsData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
      },
      form: this.$form.createForm(this),
      url: {
        approve: "/oms/omsOrder/orderApprove",
        storeInfo: "stm/stmStoreInfo/storeInfo",
        omsOrderItem: {
          list: "/oms/omsOrder/queryOmsOrderItemByMainId",
        },
      },
      loading: false,
    };
  },
  computed: {
    goodsTotalAmount() {
      if (this.goodsData.length) {
        const total = this.goodsData.reduce((sumData, item) => {
          return sumData + Number(item.productQuantity) * Number(item.realAmount);
        }, 0);
        return total.toFixed(2);
      } else {
        return 0;
      }
    },
  },
  methods: {
    show(record) {
      this.skuStockWaring=[];
      this.visible = true;
      this.model = Object.assign({}, record);
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, "productSn", "orderFlag"));
      });
      this.model.orderFlag = 1;
      this.goodsData = [];
      if (this.model.id) {
        this.loadGoodsData();
        if(this.model.creditAuthorizeFlag==1){
          this.getStoreInfo(record.storeId);
        }
      }
    },
    loadGoodsData() {
      var params = { id: this.model.id };
      this.loading = true;
      getAction(this.url.omsOrderItem.list, params).then((res) => {
        if (res.success) {
          this.goodsData = res.result.map((x) => {
            return {
              realAmount_old: x.realAmount,
              productQuantity_old: x.productQuantity,
              stock_warning: x.productQuantity > x.stock ? x.stock + "(库存不足)" : x.stock,
              IsWarning: x.productQuantity > x.stock ? 1 : 0,
              ...x,
            };
          });
          for( let i=0;i<this.goodsData.length;i++){
            if(this.goodsData[i].IsWarning==1) {
              this.skuStockWaring.push(this.goodsData[i].productName+"(库存不足)");
            }
          }
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    onChangeAmount(event, row) {
      row.realAmount = event;
    },
    onChangeQuantity(event, row) {
      row.productQuantity = event;
      if (row.stock < row.productQuantity) {
        row.stock_warning = row.stock + "(库存不足)";
        this.pushSkuWaring(row.productName+"(库存不足)");
      } else {
        row.stock_warning = row.stock;
        this.popSkuWaring(row.productName+"(库存不足)");
      }
    },
    close() {
      this.form.resetFields();
      this.$emit("close");
      this.visible = false;
    },
    handleSubmit() {
      this.confirmLoading = true;
      let itemMap = {};
      this.goodsData.forEach((row) => {
        const { productQuantity, realAmount, id } = row;
        if (
          productQuantity != row.productQuantity_old ||
          realAmount != row.realAmount_old
        ) {
          itemMap[row.id] = {
            productQuantity,
            realAmount,
            id,
          };
        }
      });
      let formData = {
        status: this.model.orderFlag,
        note: this.form.getFieldValue("note"),
        orderId: this.model.id,
        itemMap,
      };
      this.form.validateFields((err, values) => {
        if (!err) {
          httpAction(this.url.approve, formData, "put")
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.$emit("ok");
              } else {
                this.$message.warning(res.message);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
              this.close();
            });
        }
      });
      this.confirmLoading = false;
    },
    handleCancel() {
      this.close();
    },
    handleWarehouseFlag(e) {
      this.model.orderFlag = e;
      this.selectedStock = [];
      this.stockList = [];
    },
    getStoreInfo(storeId) {
      let param={};
      getAction(this.url.storeInfo+"/"+storeId, param).then(res => {
        if (res.success) {
          this.creditLimit=res.result.creditLimit;
          this.remainCreditLimit=res.result.remainCreditLimit;
          this.usedCreditLimit=res.result.usedCreditLimit;
        } else {
          console.log(res.message)
        }
      })
    },
    pushSkuWaring(msg){
      if(!this.skuStockWaring.includes(msg)){
        this.skuStockWaring.push(msg);
      }
    },
    popSkuWaring(msg){
      let index = this.skuStockWaring.indexOf(msg);
      if(index>=0){
        this.skuStockWaring.splice(index, 1)
      }
    }
  },
};
</script>
